package com.smrtcold.dev.task;

import com.alibaba.fastjson.JSONObject;
import com.smrtcold.dev.dto.dev.task.DevTask;
import com.smrtcold.dev.dto.dev.base.Point;
import com.smrtcold.dev.dto.dev.base.PointGroup;
import com.smrtcold.dev.dto.dev.base.XMZDevInfo;
import com.smrtcold.dev.dto.task.defrost.DefrostTask;
import com.smrtcold.dev.init.SystemInit;
import com.smrtcold.dev.mapper.DataMapper;
import com.smrtcold.dev.service.base.BaseServer;
import com.smrtcold.dev.service.base.DefrostMode1Service;
import com.smrtcold.dev.utils.Utils;
import lombok.extern.log4j.Log4j2;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;


/**
 * 化霜任务
 */
@Log4j2
@Service
public class SetFrostJob implements Job {


    private Long mid = 0L;

    private Long taskid;

    private int status = 0;
    @Value("${sys.apid}")
    private String apid;


    private List<String> runtime;

    @Autowired
    private DataMapper dataMapper;

    @Autowired
    private BaseServer baseServer;


    @Autowired
    private DefrostMode1Service defrostMode1Service;



    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        StringBuffer logContert = new StringBuffer();
        DevTask task = (DevTask) context.getJobDetail().getJobDataMap().get("TASK");
        this.taskid = task.getId();
        this.mid = task.getMid();
        this.runtime = task.getRuntime();
        try {
            boolean isallSuccess = this.run(logContert, task);
            status = 1;
            if (logContert.length() > 5) {
               this.baseServer. push(String.format("/%s/task/log/%s/%s", apid, mid, taskid), logContert.toString());
            }
        } catch (Exception e) {
            status = 0;
            log.error("任务执行失败：{}", e.getMessage());
            logContert.append(e.getMessage());
            //            todo 推送异常日志
            // push(String.format("HMI/%s/%s/log", apid, taskid), logContert.toString());
        }
        if (logContert.length() > 5) {
            this.dataMapper.addlog(taskid, status, 0, logContert.toString());
        }
    }

    /**
     * 执行任务
     *
     * @param logContert
     * @param
     * @throws Exception
     */
    private boolean run(StringBuffer logContert, DevTask task) throws Exception {
        String parameters = task.getParameters();
        List<PointGroup> pointGroups = JSONObject.parseArray(parameters, PointGroup.class);
        log.info("{}开始执行----------------", task.getName());
        return this.setParameters(logContert, pointGroups);
//

    }

    /**
     * 获取库温设定参数
     *
     * @param logContert
     * @param
     * @throws Exception
     */
    public boolean setParameters(StringBuffer logContert, List<PointGroup> pointGroups) throws Exception {

        if (Utils.isNull(pointGroups)) return false;
        for (PointGroup pointGroup : pointGroups) {
            XMZDevInfo xmzDevInfo = SystemInit.get(pointGroup.getDevid());
            if (null == xmzDevInfo) {
                log.warn("设备{}不存在", pointGroup.getDevid());
                continue;
            }
            this.setFrost(xmzDevInfo, pointGroup);
        }

        int mode = 0;
        Object _modie = pointGroups.get(0).getExtParams().remove("mode");
        if (null != _modie) {
            mode = Integer.parseInt(_modie.toString());
        }
        if (0 == mode) {
            this.mide1(logContert, pointGroups);
        }
        return false;
    }

    private void setFrost(XMZDevInfo xmzDevInfo, PointGroup pointGroup) throws Exception {
        HashMap<String, Object> extParams = pointGroup.getExtParams();
        for (String k : extParams.keySet()) {
            if (k.startsWith("pr_")) {
                Point p = JSONObject.parseObject(extParams.get(k).toString(), Point.class);
                extParams.put(k, xmzDevInfo.readPoint(p));
            } else {
                extParams.put(k, Double.parseDouble(extParams.get(k).toString()));
            }
        }
    }


    private void mide1(StringBuffer logContert, List<PointGroup> pointGroups) throws Exception {
        String res = "";
        List<DefrostTask> defrostTasks = this.defrostMode1Service.scheduleDefrost(this.runtime, pointGroups);

        for (DefrostTask task : defrostTasks) {
            Point fan = task.getFan();
            String[] dn = task.getGroupName().split(",");
            String[] split = fan.getAddres().split(",");
            String devid = dn[0];
            //获取小时,分钟设定
            Number hour = SystemInit.get(devid).readAddres(split[0]), minute = SystemInit.get(devid).readAddres(split[1]);
            res = String.format("读取风机%s的设定时间：%s:%s-->", fan.getName(), hour, minute);
            log.info(res);
            logContert.append(res);
            //判断时间是否需要重新设定
            if (task.getStartHour() != hour.intValue() || task.getStartMinute() != minute.intValue()) {
                SystemInit.get(devid).writeByAddres(split[0], task.getStartHour());
                SystemInit.get(devid).writeByAddres(split[1], task.getStartMinute());
                res = String.format("设置风机%s的运行时间：%s:%s", fan.getName(), task.getStartHour(), task.getStartMinute());
                log.info(res);
                logContert.append(res + "\r\n");
            } else {
                res = "化霜时间未变更";
                log.info(res);
                logContert.append(res + "\r\n");
            }
        }

    }

    /**
     * 化霜模型1........................................................
     *
     * @param pointGroup
     * @param confval
     * @param params
     */
    private void mode1(StringBuffer logContert, PointGroup pointGroup, HashMap<String, Number> confval, HashMap<String, Object> params) throws Exception {
        List<Point> points = pointGroup.getPoints();
        int size = points.size();
        Integer difruntiem = confval.get("pr_除霜运行时间").intValue();//
        int interval = confval.containsKey("interval") ? confval.get("interval").intValue() : 0;
        int maxrun = params.containsKey("maxrun") ? Integer.parseInt(params.remove("maxrun").toString()) : 1;//最大运行风机数量
        int sumdiftime = size * (difruntiem + interval);//总化霜时间

        String res = String.format("化霜时间段：%s,设定化霜时间：%s，间隔时间：%s,计划总时间：%s,同时化霜数量：%s", Utils.GSON.toJson(this.runtime), difruntiem, interval, sumdiftime, maxrun);
        log.info(res);
        logContert.append(res + "\r\n");
        //todo 时间控制
        XMZDevInfo xmzDevInfo = SystemInit.get(pointGroup.getDevid());
    }

}
